<?php
namespace app\common\model;
use app\common\library\mstching\Feie;
use app\common\library\mstching\YiLian;
use think\Request;
use think\Db;

/**
 * 门店模型
 */
class Shop extends BaseModel
{
    protected $name = 'shop';
	protected $append = ['logo','front'];

	/**
     * 关联叫号器
     */
    public function call()
    {
        return $this->hasOne('Calling','shop_id','shop_id');
    }

	 /**
     * 关联门店分类表
     */
    public function category()
    {
        return $this->belongsTo('ShopCategory');
    }
	
	/**
     * 门店头像
     */
    public function getLogoAttr($value,$data)
    {
    	if($data['logo_image_id'] == 0){
    		$wxapp = Wxapp::find();
			if(empty($wxapp['head_img'])){
				$logo = [
					'file_path' => api_url().'assets/images/shop_logo.png',
					'file_name' => 'no'
				];
			}
			$logo = [
				'file_path' => $wxapp['head_img'],
				'file_name' => 'wx'
			];
    	}else{
    		$logo_url = UploadFile::getFileName($data['logo_image_id']);
    		$logo = [
    			'file_path' => api_url() . 'uploads/' . $logo_url,
    			'file_name' => $logo_url
    		];
    	}
    	return $logo;
    }

    /**
     * 门店门头
     */
    public function getFrontAttr($value,$data)
    {
    	if($data['front_id'] == 0){
			$front = ['file_path' => api_url().'assets/images/store_logo.jpg'];
    	}else{
    		$front_url = UploadFile::getFileName($data['front_id']);
    		$front = ['file_path' => api_url() . 'uploads/' . $front_url];
    	}
    	return $front;
    }
	
    /**
     * 门店状态
     */
    public function getStatusAttr($value,$data)
    {
        $status = ['歇业中', '营业中'];
		if($value == 1){
			$time = explode('-',$data['shop_hours']);
			$start_time = explode(':',$time[0]);
			$end_time = explode(':',$time[1]);
			//判断起始时间和结束时间是否一致，如一致为24小时营业
			if((int)($start_time[0].$start_time[1]) != (int)($end_time[0].$end_time[1])){
				$start = strtotime(date('Y-m-d'.$time[0].':00',time()));
				$end = strtotime(date('Y-m-d'.$time[1].':00',time()));
				//判断结束时间是否小于开始时间，如果小于为第二天的时间
				if((int)($end_time[0].$end_time[1])<(int)($start_time[0].$start_time[1])){
					$end = $end + 60*60*24;
				}
				if(!($start<time() AND $end>time())){
					$value = 0;
				}
			}
		}
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 是否开启自动配送
     */
    public function getIsDeliveryAttr($value)
    {
        $status = ['关闭', '开启'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 是否开启骑手自动抢单
     */
    public function getIsGrabAttr($value)
    {
        $status = ['关闭', '开启'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 是否开启自动接单
     */
    public function getIsOrderAttr($value)
    {
        $status = ['关闭', '开启'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 是否开启自动配送
     */
    public function getOutShowAttr($value)
    {
        $status = ['隐藏', '显示'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 获取列表
     * @param  [type] $district 区域
     * @param  [type] $location 位置坐标
     * @param  [type] $type 类型 0=所有，10=堂食，20=外卖，30=打包，80=订桌，90排号
     * @param  [type] $shop_category_id 门店分类 0=所有
     * @param  [type] $sortType 门店排序 all=所有 range=距离最近 sales=销量最高 score=评分最高
     */
    public function getList($location='',$district='',$type=0,$shop_category_id = 0, $sortType = 'all')
    {
    	 // 筛选条件
        $filter = [];
        !empty($district) && $filter['district'] = $district;
        $shop_category_id > 0 && $filter['shop_category_id'] = $shop_category_id;
        if($type>0){
        	$type == 20 && $filter['out_show'] = 1;//外卖
    		$type == 80 && $filter['tang_mode'] = 1;//订桌
    		$type == 90 && $filter['tang_mode'] = 2;//排号
        }
        // 排序规则
        $sort = [];
        if ($sortType == 'all') {
            $sort = ['shop_id' => 'desc'];
        } 
         // 执行查询
        $list = $this->with(['category'])
            ->where($filter)
            ->order($sort)
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ]);
        //是否计算距离
		if($location){
			for($n=0;$n<sizeof($list);$n++){
				$result = getDistance($location,$list[$n]['coordinate']);
				if($result){
					$distance = $result[0]['distance'];//获取距离计算结果
					if(self::$wxapp_id > 0) {
						//获取派送设置
						$delivery =(new Setting)->getItem('delivery');
						$list[$n]['range'] = 0; //1为超出派送范围
						if($delivery['delivery_range'] < $distance){
							$list[$n]['range'] = 1; //1为超出派送范围
						}
					}
					$list[$n]['minute'] = round($result[0]['distance']/100);
					if($distance>=1000){
						$distance = sprintf("%.2f", $result[0]['distance']/1000).'km';
					}else{
						$distance = $result[0]['distance'].'m';
					}
					$list[$n]['location'] = $distance;
				}else{
					$list[$n]['location'] = '未知距离';
				}
			}
		}
        return $list;
    }

	/**
     * 获取详情
     */
    public static function detail($shop_id='',$location='')
    {
		$where = [];
		 !empty($shop_id) && $where['shop_id'] = $shop_id;
        $detail = self::with('call')->where($where)->find();
		//是否计算距离
		if($location){
			//获取派送设置
			$delivery =(new Setting)->getItem('delivery');
			$result = getDistance($location,$detail['coordinate']);
			if($result){
				$distance = $result[0]['distance'];//获取距离计算结果
				$detail['range'] = 0; //1为超出派送范围
				if($delivery['delivery_range'] < $distance){
					$detail['range'] = 1; //1为超出派送范围
				}
				if($distance>=1000){
					$distance = sprintf("%.2f", $result[0]['distance']/1000).'公里';
				}else{
					$distance = $result[0]['distance'].'米';
				}
				$detail['location'] = $distance;
			}else{
				$detail['location'] = '未知距离';
			}
		}
		return $detail;
    }
	
	/**
     * 获取所有 - api组件接口
     */
    public static function getAll($showNum=null)
    {
		$filter['status'] = 1;
		$sort = ['sort', 'shop_id' => 'desc'];
        return self::where($filter)->order($sort)->limit($showNum)->select();
    }

    /**
     * 平台获取门店列表
     
     * @return [type]           [description]
     */
    public function outList($location='',$district='',$type=0,$shop_category_id = 0, $sortType = 'all')
    {
        // 筛选条件
        $filter = [];
        !empty($district) && $filter['district'] = $district;
        $shop_category_id == 0 && $filter['shop_category_id'] = ['>',0];
        $shop_category_id > 0 && $filter['shop_category_id'] = $shop_category_id;
        if($type>0){
        	$type == 2 && $filter['food_mode'] = ['like', '%' . trim($type) . '%'];//自取
        	$type == 3 && $filter['food_mode'] = ['like', '%' . trim($type) . '%'];//外卖
        	if($type==4){
        		$filter['food_mode'] = ['like', '%1%'];//订桌
        		$filter['tang_mode'] = 1;
        	}
        	if($type==5){
        		$filter['food_mode'] = ['like', '%1%'];//排号
        		$filter['tang_mode'] = 2;
        	}
        }

        // 排序规则
        $sort = [];
        if ($sortType === 'all') {
            $sort = ['shop_id' => 'desc'];
        } 
        // 执行查询
        $list = $this->useGlobalScope(false)->with(['category'])
            ->where($filter)
            ->order($sort)
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ]);
        //是否计算距离
		if($location){
			for($n=0;$n<sizeof($list);$n++){
				$result = getDistance($location,$list[$n]['coordinate']);
				if($result){
					$distance = $result[0]['distance'];//获取距离计算结果
					$list[$n]['minute'] = round($result[0]['distance']/100);
					if($distance>=1000){
						$distance = sprintf("%.2f", $result[0]['distance']/1000).'km';
					}else{
						$distance = $result[0]['distance'].'m';
					}
					$list[$n]['location'] = $distance;
				}else{
					$list[$n]['location'] = '未知距离';
				}
			}
		}
        return $list;
    }
	
	/**
     * 新增默认门店
     */
    public function insertDefault($wxapp_id,$data)
    {
		// 开启事务
        Db::startTrans();
        try {
			// 添加默认门店
			$this->save([
				'shop_name' => $data['shop_name'],
				'linkman' => $data['linkman'],
				'shop_hours' => '08:00-21:00',
				'phone' => $data['phone'],
				'tang_mode' => 2,//排号点餐
				'wxapp_id' => $wxapp_id,
			]);
			// 新增默认店长
			$clerk = new ShopClerk;
			$clerk->insertDefault($this->shop_id,$data,$wxapp_id);
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
	
	/**
     * 批量删除门店数据
     */
    public function deleteBatch($wxapp_id='',$shop_id='')
    {
		$where = [];
		!empty($wxapp_id) && $where['wxapp_id'] = $wxapp_id;
		!empty($shop_id) && $where['shop_id'] = $shop_id;
		$list = $this->select();
		if(!empty($shop_id)){
			if(sizeof($list)==1){
				$this->error = '至少保留一个门店';
				return false;
			}
		}
		// 开启事务
        Db::startTrans();
        try {
			//充值记录
			Recharge::where($where)->delete();
			//打印机
			$printer_list = Printer::where($where)->select();
			Printer::where($where)->delete();
			//打印任务
			PrinterLog::where($where)->delete();
			//餐桌包间
			$table_list = Table::where($where)->select();
			Table::where($where)->delete();
			//店员数据
			ShopClerk::where($where)->delete();
			//产品分类
			Category::where($where)->delete();
			//订单
			$orderIds = Order::where($where)->column('order_id');
			Order::where($where)->delete();
			if($orderIds){
				OrderAddress::where(['order_id' => ['in', $orderIds]])->delete();
				OrderGoods::where(['order_id' => ['in', $orderIds]])->delete();
			}
			//预约订单
			Pact::where($where)->delete();
			//店员数据
			Comment::where($where)->delete();
			//删除门店
			Shop::where($where)->delete();
			//删除产品
			if($shop_id > 0){
				$fileName = [];
				//产品
				$goodsIds = Goods::where($where)->column('goods_id');//获取所有要删除的产品ID
				Goods::where($where)->delete();//删除所有产品
				if($goodsIds){
					GoodsSpec::where(['goods_id' => ['in', $goodsIds]])->delete();//删除规格名称
					GoodsSpecRel::where(['goods_id' => ['in', $goodsIds]])->delete();//删除规格属性
					//$imageIds = GoodsImage::where(['goods_id' => ['in', $goodsIds]])->column('image_id');//获取要删除的产品图片ID
					GoodsImage::where(['goods_id' => ['in', $goodsIds]])->delete();//删除产品图片集
					//过滤重复的数组数据并重新排序
					//$imageIds = array_values(array_flip(array_flip($imageIds)));
				}
			}else{
				Goods::where($where)->delete();//删除所有产品	
				GoodsSpec::where($where)->delete();//删除规格属性
				GoodsSpecRel::where($where)->delete();//删除规格属性
				GoodsImage::where($where)->delete();//删除产品图片集
				$fileName = UploadFile::where($where)->column('file_name');//获取所有要删除的产品图片
				UploadFile::where($where)->delete();//删除图片
				UploadGroup::where($where)->delete();//删除图片分组
			}
			//删除产品图片
			for($n=0;$n<sizeof($fileName);$n++){
				if(file_exists('./uploads/'.$fileName[$n]))
				{
					unlink('./uploads/'.$fileName[$n]);
				}
			}
			//门店二维码
			if($shop_id > 0){
				if(file_exists('./assets/qrcode/shop/'.$shop_id.'.png'))
				{
					unlink('./assets/qrcode/shop/'.$shop_id.'.png');
				}
            }else{
				for($n=0;$n<sizeof($list);$n++){
					if(file_exists('./assets/qrcode/shop/'.$list[$n]['shop_id'].'.png'))
					{
						unlink('./assets/qrcode/shop/'.$list[$n]['shop_id'].'.png');
					}
				}
			}
			//餐桌二维码
			for($n=0;$n<sizeof($table_list);$n++){
				if(file_exists('./assets/qrcode/table/'.$table_list[$n]['table_id'].'.png'))
				{
					unlink('./assets/qrcode/table/'.$table_list[$n]['table_id'].'.png');
				}
			}
			//云端删除打印机
			for($n=0;$n<sizeof($printer_list);$n++){
				if($printer_list[$n]['brand']['value']==20){
					$client = new Feie();
					if(!$client->printerDelList($printer_list[$n]['open_user_id'])){
						$this->error = '云端删除失败';
						return false;
					}
				}
				if($printer_list[$n]['brand']['value']==30){
					$client = new YiLian();
					if($err = $client->printerDel($printer_list[$n]['open_user_id'])){
						$this->error = $err;
						return false;
					}
				}
			}
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
}
